import torch
import torchaudio
import matplotlib.pyplot as plt

# 检查音频的元信息
metadata = torchaudio.info("test.wav")
"""
sample_rate=22050 是音频的采样率
num_frames=63693 是每通道的帧数
num_channels=1 是通道数
bits_per_sample=16 是位深
encoding=PCM_S 是采样编码格式
"""
print(metadata)

# waveform 波形（channels 通道数,frames 帧数）
# sample_rate 采样率
waveform, sample_rate = torchaudio.load("test.wav")
print(waveform.shape, sample_rate)
# waveform 的形态 [1, 63693]
# sample_rate 的采样率 22050

# 展示声音形态
def plot_waveform(waveform, sample_rate):
    # 振幅
    waveform = waveform.numpy()

    num_channels, num_frames = waveform.shape
    # 时序
    time_axis = torch.arange(0, num_frames) / sample_rate

    figure, axes = plt.subplots(num_channels, 1)
    if num_channels == 1:
        axes = [axes]
    for c in range(num_channels):
        axes[c].plot(time_axis, waveform[c], linewidth=1)
        axes[c].grid(True)
        if num_channels > 1:
            axes[c].set_ylabel(f"Channel {c + 1}")
    figure.suptitle("waveform")


plot_waveform(waveform, sample_rate)
plt.show()
